<template>
  <div class="interact-layout">
    <ul class="interact-list">
      <li
        v-for="(item, index) of interactist"
        :key="item.label"
        @click="handleModule(item, index)"
        :class="{ 'active-li': activeIndex === index }"
      >
        {{ item.label }}
      </li>
    </ul>
    <div class="table-form">
      <!-- <div class="title">{{ $t("title.interactConfig") }}</div> -->
      <el-form
        ref="formRef"
        :model="form"
        :inline="true"
        class="pro-select-box"
      >
        <el-form-item
          :label="$t('system.interactConfig.dataNumber')"
          prop="dataCode"
        >
          <el-input
            v-model="form.dataCode"
            class="form-input"
            clearable
            :placeholder="$t('system.interactConfig.dataNumber')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('system.interactConfig.dataName')"
          prop="dataName"
        >
          <el-input
            v-model="form.dataName"
            class="form-input"
            clearable
            :placeholder="$t('system.interactConfig.dataName')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('system.interactConfig.dataType')"
          prop="dataType"
        >
          <el-input
            v-model="form.dataType"
            class="form-input"
            clearable
            :placeholder="$t('system.interactConfig.dataType')"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="checkList">{{
            $t("common.queryText")
          }}</el-button>
          <!-- v-permission="['system:interactiveTable:export']" -->
          <!-- @click="handleExport" -->

          <el-button
            type="primary"
            :loading="exportLoading"
            icon="Share"
            @click="handleExport"
          >
            <a :href="downUrl" download class="download">{{
              $t("common.export")
            }}</a>
          </el-button>
          <!-- v-permission="['system:interactiveTable:import']" -->
          <el-button type="primary" @click="handleImport" icon="Upload">{{
            $t("common.import")
          }}</el-button>
          <!-- <el-button type="primary" @click="setCol">列设置</el-button> -->
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <hcTable
        :table-data="tableData"
        :options="tableOptions"
        :columns="showCol"
        @command="handleAction"
        @size-change="handlerPageSize"
        @current-change="handlerPageIndex"
      >
        <template #isSpc="{ row }">
          <el-tag :type="row.isSpc ? 'success' : 'danger'">
            {{ row.isSpc ? $t("common.yes") : $t("common.no") }}
          </el-tag>
        </template>
      </hcTable>
      <!-- 新增、编辑设备弹框 -->
      <Interact-dialog
        :options="options"
        @onCancel="closeDialog"
        @onSure="onSure"
      />
      <!-- 文件弹框 -->
      <div>
        <input v-show="false" ref="fileRef" type="file" @change="getFile" />
      </div>
    </div>
    <!-- <SetColumn
      :options="optionsCol"
      :selectedCol="selectedCol"
      @onCancel="closeCol"
      @onSure="saveCol"
    /> -->
    <Progress v-model="exportLoading" v-if="exportLoading" />
  </div>
</template>

<script setup>
import { reactive, ref, toRefs, computed, unref, toRaw, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { exportExcel, importExcel, getLoadChild } from "@/api/config";
import useTable from "@/hooks/useTable";
import InteractDialog from "./components/interact-dialog.vue";
import { listConvertTree } from "@/utils";
import { useI18n } from "vue-i18n";
// import SetColumn from "@/components/set-colunm/index.vue";
import Progress from "@/components/progress";
import dayjs from "dayjs";
import getEnvConfig from "@/config/axios/getEnvConfig";

const { t: $t } = useI18n();

let downUrl = getEnvConfig.VITE_BASE_URL + "/ProductDataSetting/ExportExcel";
let readUrl = `/ProductDataSetting`;
const { list, total, loading, getList, updateFun } = useTable(
  readUrl,
  true,
  false
);

onMounted(() => {
  getList(params.value);
});

const formRef = ref();

const tableALLColumn = [
  {
    type: "index",
    width: "50",
    label: "No.",
    align: "center",
    fixed: true,
  },
  {
    prop: "equipmentName",
    label: $t("system.interactConfig.deviceName"),
    width: "120",
    fixed: true,
    showOverflowTooltip: true,
  },
  {
    prop: "equipmentCode",
    label: $t("system.interactConfig.deviceNumber"),
    width: "110",
    showOverflowTooltip: true,
  },
  {
    prop: "siteName",
    label: $t("system.interactConfig.stationName"),
    width: "120",
    showOverflowTooltip: true,
  },
  {
    prop: "dataCode",
    width: "180",
    label: $t("system.interactConfig.dataNumber"),
    showOverflowTooltip: true,
  },
  {
    prop: "siteCode",
    label: $t("system.interactConfig.stationNumber"),
    width: "110",
    showOverflowTooltip: true,
  },
  {
    prop: "dataName",
    width: "150",
    label: $t("system.interactConfig.dataName"),
    showOverflowTooltip: true,
  },
  {
    prop: "parentCode",
    label: $t("system.interactConfig.arrayNumber"),
    width: "100",
    showOverflowTooltip: true,
  },
  {
    prop: "index",
    label: $t("system.interactConfig.arrayIndex"),
    width: "110",
    showOverflowTooltip: true,
  },
  {
    prop: "dataType",
    label: $t("system.interactConfig.dataType"),
    width: "100",
    showOverflowTooltip: true,
  },
  {
    prop: "dataLength",
    label: $t("system.interactConfig.dataLength"),
    width: "110",
    showOverflowTooltip: true,
  },
  {
    prop: "plcAddress",
    label: $t("system.interactConfig.PLCAddress"),
    width: "180",
    showOverflowTooltip: true,
  },
  {
    prop: "interval",
    label: $t("system.interactConfig.collectionFrequency"),
    width: "170",
    showOverflowTooltip: true,
  },
  {
    prop: "isSpc",
    label: $t("system.interactConfig.SpcOrNot"),
    width: "120",
    slot: "isSpc",
    showOverflowTooltip: true,
  },
  {
    prop: "category",
    label: $t("system.interactConfig.classification"),
    width: "120",
    showOverflowTooltip: true,
  },
  // {
  //   width: "100",
  //   label: $t("common.operate"),
  //   align: "center",
  //   fixed: "right",
  //   buttons: [
  //     {
  //       name: "read",
  //       type: "primary",
  //       command: "edit",
  //       // permission: ["system:interactiveTable:del"],
  //     },
  //   ],
  // },
];

let selectedCol = ref(tableALLColumn.map((i) => i.label));
const interactist = [
  {
    label: $t("system.interactConfig.product"),
    value: 6,
  },
  {
    label: $t("system.interactConfig.abnormal"),
    value: 2,
  },
  {
    label: $t("system.interactConfig.fault"),
    value: 3,
  },
];

const data = reactive({
  // 绑定数据
  form: {
    dataCode: "",
    dataName: "",
    dataType: "",
    category: 6,
  },
  page: {
    pageSize: 10,
    pageIndex: 1,
  },
  options: {
    show: false,
    type: "", // 用于判断是编辑还是删除 add edit
    curEqui: null,
  },
  showCol: tableALLColumn,
  optionsCol: {
    show: false,
    colList: tableALLColumn,
  },
});

const tableData = computed(() => {
  let arr = [];
  if (list.value.length) {
    arr = listConvertTree(list.value);
  }
  return arr;
});

const tableOptions = computed(() => {
  return {
    loading: loading.value,
    showPagination: true,
    border: true,
    rowKey: "id",
    treeProps: { children: "children", hasChildren: "hasChildren" },
    lazy: true,
    load: handleLoad,
    paginationConfig: {
      total: total.value,
      currentPage: data.page.pageIndex,
      pageSize: data.page.pageSize,
    },
  };
});

const handleLoad = async (row, treeNode, resolve) => {
  const res = await getLoadChild(readUrl, {
    parentCode: row.dataCode,
  });
  resolve(res.items);
};

const params = computed(() => {
  let form = JSON.parse(JSON.stringify(data.form));
  Object.keys(form).forEach((key) => {
    if (form[key] === null) {
      form[key] = "";
    }
  });
  return {
    ...form,
    ...data.page,
  };
});
// 操作事件
const handleAction = (command, row) => {
  switch (command) {
    case "edit":
      handlerEdit(row);
      break;
    default:
      break;
  }
};
// 点击查询
const checkList = () => {
  data.page.pageIndex = 1;
  getList(params.value);
};
// 表请求条数改变
const handlerPageSize = (pageSize) => {
  data.page.pageSize = pageSize;
  data.page.pageIndex = 1;
  getList(params.value);
};
// 表格页数改变
const handlerPageIndex = (pageIndex) => {
  data.page.pageIndex = pageIndex;
  getList(params.value);
};
// 导出
const exportLoading = ref(false);
const handleExport = async () => {
  exportLoading.value = true;
  // const res = await exportExcel().catch(() => {
  //   exportLoading.value = false;
  // });
  // const date = dayjs(new Date().getTime())
  //   .format("YYYY-MM-DD HH:mm:ss")
  //   .toString();
  // await exportByBlob(res, date + "数据交互表");
  let t = setTimeout(() => {
    exportLoading.value = false;
    clearTimeout(t);
  }, 2000);
};
// 导入
const fileRef = ref(null);
const handleImport = () => {
  fileRef.value.click(); // 打开选择文件的弹框
};
const getFile = async (e) => {
  let formDate = new FormData();
  formDate.append("file", e.target.files[0]);
  await importExcel(formDate);
  ElMessage({
    message: "导入成功",
    type: "success",
    duration: 1000,
  });
  getList(params.value);
};
// 编辑
const handlerEdit = (item) => {
  data.options = {
    show: true,
    type: "edit", // 用于判断是编辑还是删除 add edit
    curEqui: item,
  };
};
// 保存弹框
const onSure = async (options) => {
  if (options.type === "add") {
  } else {
    updateFun(options.id, options.form, readUrl);
  }
  closeDialog();
};
// 关闭弹框
const closeDialog = () => {
  data.options = {
    show: false,
    type: "", // 用于判断是编辑还是删除 add edit
    curEqui: null,
  };
};

let activeIndex = ref(0);
const handleModule = (item, index) => {
  if (unref(activeIndex) === index) return;
  activeIndex.value = index;
  data.form.category = item.value;
  getList(params.value);
};

// 列设置
const setCol = () => {
  data.optionsCol.show = true;
};

const saveCol = (item) => {
  data.showCol = tableALLColumn.filter((i) => toRaw(item).includes(i.label));

  data.optionsCol.show = false;
};

const closeCol = () => {
  data.optionsCol.show = false;
};

const { form, options, optionsCol, showCol } = toRefs(data);
</script>
<style lang="scss" scoped>
.interact-layout {
  height: 100%;
  display: flex;
}
.table-form {
  flex: 1;
  .title {
    text-align: center;
    margin-bottom: 10px;
    font-size: 24px;
  }
}
.download {
  text-decoration: none;
  color: #fff;
}
.interact-list {
  padding-top: 11px;
  padding-right: 10px;
  overflow: auto;
  height: 100%;
  width: 10%;
  border-right: 1px solid #0084fe;
  li {
    height: 36px;
    width: 100%;
    color: #0084fe;
    font-size: 16px;
    padding: 8px 11px;
    border-right: 3px solid transparent;
    cursor: pointer;
  }
  .active-li {
    background: rgba(0, 75, 144, 0.3);
    border-right: 3px solid #0084fe;
    color: #ffffff;
  }
}
</style>
